package com.quickstart.user.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.quickstart.common.mybatis.page.PageForm;
import com.quickstart.entity.UserEntity;
import com.quickstart.user.form.UserForm;
import com.quickstart.user.model.UserModel;
import com.quickstart.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:wesley
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping(value = "/get/{id}")
    @ResponseBody
    public UserEntity getUserById(@PathVariable("id") Integer id){
        if(id != null){
            UserEntity userEntity = userService.getUserById(id);
            return userEntity;
        } else {
            UserEntity userEntity = new UserEntity();
            userEntity.setId(-1);
            userEntity.setName("用户不存在");
            return userEntity;
        }
    }



    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String,Object> getUserList(PageForm pageForm, UserForm userForm){
        PageHelper.startPage(pageForm.getPage(),pageForm.getLimit());
        List<UserModel> userList = userService.getUserList(userForm);
        PageInfo<UserModel> pageInfo = new PageInfo<>(userList);

        Map<String,Object> map = new HashMap<>();
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        map.put("code","");
        map.put("msg","");
        return map;
    }




    @RequestMapping(value = "/saveOrUpdate")
    @ResponseBody
    public Map<String,Object> saveOrUpdate(String dataStr){
        Map<String, Object> map = new HashMap<>();
        UserEntity userEntity = JSON.parseObject(dataStr,UserEntity.class);

        if(userEntity.getId() == null){
            int tag = userService.save(userEntity);
            if(tag > 0){
                map.put("tag",true);
            } else {
                map.put("msg","保存失败");
                map.put("tag",false);
            }
        } else {
            int tag = userService.update(userEntity);
            if(tag > 0){
                map.put("tag",true);
            } else {
                map.put("msg","更新失败");
                map.put("tag",false);
            }

        }
        return map;
    }


}
